package com.test.moudle.sys.oauth2;

import com.test.moudle.sys.entity.Token;
import com.test.moudle.sys.entity.User;
import com.test.moudle.sys.service.TokenService;
import com.test.moudle.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 执行时机：
     * 自己去调用这个是否有什么角色或者是否有什么权限的时候 - Subject currentUser = SecurityUtils.getSubject()
     * 或
     * 在方法上加注解的时候 - @RequiresRoles("admin")
     * 或
     * 略，用不到
     *
     * @param principals 一个身份集合，其包含了Realm验证成功的身份信息
     * @return 认证信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        User user = (User) principals.getPrimaryPrincipal();
        log.info("doGetAuthorizationInfo User|{}", user);

        // 用户权限列表
        Set<Permission> permsSet = userService.findPermissions(user.getId());
        log.info("用户权限列表|{}", permsSet);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setObjectPermissions(permsSet);

        return info;
    }

    /**
     * 执行时机：
     * Subject currentUser = SecurityUtils.getSubject();
     * Subject currentUser = SecurityUtils.getSubject();
     *
     * @param token token
     * @return 认证信息
     * @throws AuthenticationException AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        log.debug("doGetAuthenticationInfo");

        String accessToken = (String) token.getPrincipal();

        // 根据accessToken，查询用户信息
        Token tokenEntity = tokenService.findByToken(accessToken);
        // token失效
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        // 查询用户信息
        User user = userService.findById(tokenEntity.getUserId());
        log.info("user|{}", user);
        // 账号锁定
        if (user.getStatus() == 1) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        return new SimpleAuthenticationInfo(user, accessToken, getName());
    }
}
